#include "mainwindow.h"
#include "start.h"
#include <QString>
#include "mutigame.h"
#include <iostream>

//shop : 购买栏
//shovel : 小推车
//button : 暂停
//map : 地图
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setFixedSize(900,600);
    startPage = new start();
    mutigamePage = new MutiGame();
    startPage->show();
    setCentralWidget(startPage);
    connect(startPage, SIGNAL(enterGame(QString)), this, SLOT(showWaitingRoom(QString)));
}

MainWindow::~MainWindow()
{

}


void MainWindow::showWaitingRoom(QString username)
{
    this->username = username;
    waitingPage = new waitingroom(username, this);
    setCentralWidget(waitingPage);
    startPage->hide();
    waitingPage->show();
    initClient();

}

void MainWindow::showMutiGame()
{
    std::cout << "Entering showMutiGame()" << std::endl;
    mutigamePage->init(transiver);
    mutigamePage->show();
    setCentralWidget(mutigamePage);
    waitingPage->hide();
}

void MainWindow::setFaction(int select, QString username)
{
    waitingPage->setPlayer(select, username);
    if(QString::compare(username, this->username) == 0)
    {
        mutigamePage->setFaction(static_cast<MutiGame::Faction>(select));
    }
}


void MainWindow::initClient()
{
    //创建client对象
    client = new QTcpSocket(this);

    if(client->state()==QAbstractSocket::ConnectedState){
            //如果使用disconnectFromHost()不会重置套接字，isValid还是会为true
        client->abort();
    }else if(client->state()==QAbstractSocket::UnconnectedState){
        const QHostAddress address=QHostAddress("127.0.0.1");
        const unsigned short port=3240;
            //连接服务器
        client->connectToHost(address,port);
    }else{
        QMessageBox::about(this, "error", "can not connect to the server");
    }

    //连接状态
    connect(client,&QTcpSocket::connected,[this]{
        transiver = new Transiver(username, client, 1);

        connect(transiver, SIGNAL(broadCast(int,QString)), this, SLOT(setFaction(int, QString)));
        connect(transiver, SIGNAL(GameStart()), this, SLOT(showMutiGame()));
        connect(client,&QTcpSocket::readyRead,[this]{
            if(client->bytesAvailable()<=0)
                return;
            QByteArray jsonBytes;
            jsonBytes.append(client->readAll());

            QList<QByteArray>subarrays = jsonBytes.split('^');

            subarrays.removeLast();

            if(!subarrays.isEmpty())
            {
                QList<QByteArray>::iterator it1 = subarrays.begin();
                for(; it1!=(subarrays.end()); ++it1)
                {
                    transiver->parse(*it1);
                }
            }

        });
        transiver->sendMsg(1);
    });



}
